package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"io"
	"log"
	"net"
	hs "xiaohuasheng.cc/user/hello/grpc/HelloService"
)
type HelloServiceImpl struct {
	hs.UnimplementedHelloServiceServer
}

func (p *HelloServiceImpl) Hello(ctx context.Context, args *hs.String,
	) (*hs.String, error) {
	reply := &hs.String{Value: "hello:" + args.GetValue()}
	return reply, nil
}

func (p *HelloServiceImpl) Channel(stream hs.HelloService_ChannelServer) error {
	for {
		args, err := stream.Recv()
		if err != nil {
			if err == io.EOF {
				fmt.Println("客户端关闭真会到这里吗？")
				return nil
			}
			fmt.Println("还是这里?", err)
			return err
		}

		val := args.GetValue()
		if val == "finish" {
			return io.EOF
		}

		reply := &hs.String{Value: "hello:" + val}

		err = stream.Send(reply)
		if err != nil {
			return err
		}
	}
}

func main() {
	fmt.Println("start a grpc server")
	grpcServer := grpc.NewServer()
	hs.RegisterHelloServiceServer(grpcServer, new(HelloServiceImpl))

	lis, err := net.Listen("tcp", ":1234")
	if err != nil {
		log.Fatal(err)
	}
	grpcServer.Serve(lis)
}
